package com.shop.servlet.user;

import com.mysql.jdbc.StringUtils;
import com.shop.pajo.Book;
import com.shop.pajo.ShoppingCart;
import com.shop.pajo.User;
import com.shop.service.user.UserService;
import com.shop.service.user.UserServiceImpl;
import com.shop.utils.CommunityUtil;
import com.shop.utils.Constants;
import com.shop.utils.CookieUtil;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method != null && method.equals("login")) {
            login(req, resp);
        }
        if(method != null && method.equals("logout")) {
            logout(req, resp);
        }
        if(method != null && method.equals("verification")) {
            verification(req, resp);
        }
        if(method != null && method.equals("register")) {
            register(req, resp);
        }
        if(method != null && method.equals("add_to_cart")) {
            addToCart(req, resp);
        }
        if(method != null && method.equals("toCart")) {
            toCart(req, resp);
        }
        if(method != null && method.equals("deleteCart")) {
            deleteCart(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    public void login(HttpServletRequest request, HttpServletResponse response) {

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        String code = request.getParameter("code");

        String rememberme = request.getParameter("rememberme");

        HttpSession session = request.getSession();
        String kaptcha = (String)session.getAttribute("kaptcha");

        if(StringUtils.isNullOrEmpty(kaptcha) || StringUtils.isNullOrEmpty(code) || !kaptcha.equalsIgnoreCase(code)) {
            request.setAttribute("codeMsg","验证码不正确");

            try {
                request.getRequestDispatcher("/jsp/user/userLogin.jsp").forward(request, response);
                return;
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        UserService userService = new UserServiceImpl();
        //检查账号密码
        int expriedSeconds = rememberme!=null ? Constants.REMEMBER_EXPIRED_SECONDS : Constants.DEFAULT_EXPIRED_SECONDS;
        Map<String, Object> map = userService.login(username, password, expriedSeconds);

        if(map.containsKey("ticket")) {
            //将登录凭证保存在用户本地
            Cookie cookie = new Cookie("ticket",map.get("ticket").toString());
            cookie.setPath(request.getContextPath()+ "/");
            cookie.setMaxAge(expriedSeconds);
            response.addCookie(cookie);

            CommunityUtil.JumpIn1Seconds(response, "/");

        } else {
            request.setAttribute("usernameMsg",map.get("usernameMsg"));
            request.setAttribute("passwordMsg",map.get("passwordMsg"));
            request.setAttribute("username", username);
            try {
                request.getRequestDispatcher("/jsp/user/userLogin.jsp").forward(request, response);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void logout(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        String ticket = CookieUtil.getValue(request, "ticket");
        session.removeAttribute("userSession");

        UserService userService = new UserServiceImpl();
        userService.logout(ticket);

        try {
            response.sendRedirect("/");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void verification(HttpServletRequest request, HttpServletResponse response) {
        UserService userService = new UserServiceImpl();
        String username = request.getParameter("username");
        User user = userService.getUserByName(username);
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            if(user == null) {
                writer.print("true");
            }else {
                writer.print("false");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }
    }

    public void register(HttpServletRequest request, HttpServletResponse response) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");

        //验证码验证
        String code = request.getParameter("code");
        HttpSession session = request.getSession();
        String kaptcha = (String)session.getAttribute("kaptcha");
        if(StringUtils.isNullOrEmpty(kaptcha) || StringUtils.isNullOrEmpty(code) || !kaptcha.equalsIgnoreCase(code)) {
            request.setAttribute("codeMsg","验证码不正确");

            try {
                request.getRequestDispatcher("/jsp/user/userRegister.jsp").forward(request, response);
                return;
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //对象创建
        User user = new User();
        user.setName(username);
        user.setPassword(password);
        user.setEmail(email);
        //执行注册事务
        UserService userService = new UserServiceImpl();
        Map<String, Object> map = userService.register(user);

        if(map == null || map.isEmpty()) {
            try {
                response.sendRedirect("/jsp/user/userLogin.jsp");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else {
            request.setAttribute("usernameMsg",map.get("usernameMsg"));
            request.setAttribute("passwordMsg",map.get("passwordMsg"));
            request.setAttribute("emailMsg",map.get("emailMsg"));

            try {
                request.getRequestDispatcher("/jsp/user/userRegister.jsp").forward(request, response);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void addToCart(HttpServletRequest request, HttpServletResponse response) {

        String bid = request.getParameter("bid");
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute(Constants.USER_SESSION);
        if(user == null) {
            request.getSession().setAttribute("error","当前未登录！");
            CommunityUtil.JumpIn1Seconds(response, "/");
            return;
        }
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUid(user.getId());
        shoppingCart.setBid(bid);

        UserService userService = new UserServiceImpl();
        Map<String, Object> map = userService.addToCart(shoppingCart);

        if(map == null || map.isEmpty()) {
            request.getSession().setAttribute("tips", "书籍添加购物车成功！");
            CommunityUtil.JumpIn1Seconds(response, "/");
        } else {
            request.getSession().setAttribute("error", map.get("error"));
            CommunityUtil.JumpIn1Seconds(response, "/");
        }

    }

    public void toCart(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute(Constants.USER_SESSION);
        if(user == null) {
            request.getSession().setAttribute("error","当前未登录！");
            CommunityUtil.JumpIn1Seconds(response, "/");
            return;
        }
        UserService userService = new UserServiceImpl();
        List<Book> books = userService.getCart(user.getId());
        session.setAttribute("books", books);
        CommunityUtil.JumpIn1Seconds(response, "/jsp/user/shopping.jsp");
    }

    public void deleteCart(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        String bid = request.getParameter("bid");
        User user = (User)session.getAttribute(Constants.USER_SESSION);
        if(user == null) {
            request.getSession().setAttribute("error","当前未登录！");
            CommunityUtil.JumpIn1Seconds(response, "/");
            return;
        }

        UserService userService = new UserServiceImpl();
        int i = userService.deleteCart(bid);

        CommunityUtil.JumpIn1Seconds(response, "/jsp/user/user.do?method=toCart");
    }
}
